package com.wnxy.portal.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/portal")
@Slf4j
public class PortalController {

    // 依赖注入（Dependency Injection）容器中RestTemplate类型的对象
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 需求：当前门户微服务端口是9001，需要访问会员微服务9000 http://localhost:9001/portal/123
     * 实现：通过RestTemplate实现远程调用！
     */
    @RequestMapping("/{mid}")
    public String findMemberById(String mid){
        String url = "http://localhost:9000/member/"+mid;
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    @RequestMapping("/member/{mid}")
    public String findMember(String id){
        // 根据服务名称，获取服务实例对象，通过list集合接收，因为服务有可能是集群
        List<ServiceInstance> instances = discoveryClient.getInstances("cinema-member-service");
        // 因为微服务没有做集群，所以这里只要获取第一个服务实例即可
        ServiceInstance serviceInstance = instances.get(0);

        // 获取主机、端口
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();

        String url = "http://"+host+":"+port+"/member/"+id;
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    //Ribbon默认的负载均衡策略是轮询RoundRobinRule，
    // 若要修改负载均衡策略，可以在配置文件中配置为随机策略RandomRule
    @GetMapping("/member/lb/{mid}")
    public String findMember2(@PathVariable("mid")String mid) {
        String url = "http://cinema-member-service/member/"+mid;
        return restTemplate.getForObject(url,String.class);
    }
}
